/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.healthecology.data.utils;

import java.util.Optional;
import java.util.function.Consumer;

/**
 * The helper for optional instance, to support Java 9 operation orElseGet()
 */
public class OptionalX<T> {
    private final Optional<T> optional;

    private OptionalX(Optional<T> optional) {
        this.optional = optional;
    }

    /**
     * Constructs an instance with the value present
     *
     * @param optional The non-null optional value to be present
     * @param <T> The class type
     * @return A instance of optionalx
     */
    public static <T> OptionalX<T> of(Optional<T> optional) {
        if (optional == null) {
            return new OptionalX<>(Optional.empty());
        } else {
            return new OptionalX<>(optional);
        }
    }

    /**
     * Constructs an instance with the value present
     *
     * @param object The non-null optional value to be present
     * @param <T> The class type
     * @return A instance of optionalx
     */
    public static <T> OptionalX<T> ofNullable(T object) {
        return new OptionalX<>(Optional.ofNullable(object));
    }

    /**
     * If a value is present, invoke the specified consumer with the value,
     * otherwise do nothing.
     *
     * @param consumer Block to be executed if a value is present
     * @return The result of applying an {@code Optional}-bearing mapping
     * function to the value of this {@code Optional}, if a value is present
     */
    public OptionalX<T> ifPresent(Consumer<T> consumer) {
        if (consumer == null) {
            return this;
        }
        optional.ifPresent(consumer);
        return this;
    }

    /**
     * If a value is not present, invoke the specified runnable with the value,
     * otherwise do nothing.
     *
     * @param runnable The runnable should be executed
     * @return The result of applying the runnable, if a value is not present
     */
    public OptionalX<T> ifNotPresent(Runnable runnable) {
        if (!optional.isPresent() && runnable != null) {
            runnable.run();
        }
        return this;
    }
}
